package com.szewec.ps.ui.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mapapi.model.LatLng;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.base.ListBaseAdapter;
import com.szewec.ps.base.SuperViewHolder;
import com.szewec.ps.databinding.ActivityTaskEditBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.project.ProjectListModel;
import com.szewec.ps.model.project.SelectUserModel;
import com.szewec.ps.model.task.SurveyObjectModel;
import com.szewec.ps.model.task.TaskCountModel;
import com.szewec.ps.model.task.TaskDTOModel;
import com.szewec.ps.model.task.TaskListModel;
import com.szewec.ps.model.task.TaskUserModel;
import com.szewec.ps.model.user.UserModel;
import com.szewec.ps.myinterface.IUserInfo;
import com.szewec.ps.myview.BaseInput;
import com.szewec.ps.myview.pickerview.TimePickerView;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.member.MemberSelectActivity;
import com.szewec.ps.ui.road.facilities.intersection.task.constants.Consts;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.ViewUtils;
import com.szewec.ps.ui.road.facilities.intersection.task.views.IteamSlideLayout;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.CoorModelChangeUtil;
import com.szewec.ps.util.DateUtil;
import com.szewec.ps.util.OneOffCupboard;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.dialog.LoadingDialog;
import com.szewec.ps.util.okhttp.OkHttp;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

public class TaskEditActivity extends BaseActivity {
    private ActivityTaskEditBinding _binding;
    private LoadingDialog _loadingDialog;

    private static final int SURVEY_OBJECT_MAX = 9; // 调查对象最大数量
    private static final int USER_TYPE_WORKER = 1; // 人员类型 任务人
    private static final int USER_TYPE_CC = 2; // 人员类型 抄送人

    /********字典start***********/
    // 调查类型
    private ArrayList<String> surveyTypeDict = new ArrayList<>();
    // 基础设施调查子项
    private ArrayList<String> surveyTypeChildDict = new ArrayList<>();
    /********字典end***********/

    private String ModeFlag_Add_Edit_View; //标志当前界面是详情模式，还是新增模式，还是编辑模式!
    private ProjectListModel.ProjectModel projectModel = new ProjectListModel.ProjectModel();
    private TaskListModel.TaskVO taskVO = new TaskListModel.TaskVO();
    private TaskDTOModel dtoModel = new TaskDTOModel();
    private SurveyObjectDataAdapter surveyObjectDataAdapter;
    private List<SurveyObjectModel> surveyObjectList = new ArrayList<>(); // 调查对象List
    private List<? extends IUserInfo> _selectedWorkerList = new ArrayList<>(); // 任务人
    private List<? extends IUserInfo> _selectedCCList = new ArrayList<>(); // 抄送人
    private List<TaskUserModel> workerUserList = new ArrayList<>(); // 任务人列表
    private List<TaskUserModel> ccUserList = new ArrayList<>(); // 抄送人列表
    private Integer surveyType;
    private String maxTaskNumber = "01";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        _binding = DataBindingUtil.setContentView(this, R.layout.activity_task_edit);
        ButterKnife.bind(this);
        _loadingDialog = LoadingDialog.getInstance(this);

        initData();
        initView();
        initTitleBar();
        initRecycleView();
        addSurveyObject();
    }

    private void initData() {
        surveyTypeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.surveyType)));
        surveyTypeChildDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.surveyTypeChild)));
        PresentValue<Map<String, Object>> presentValue = (PresentValue<Map<String, Object>>) getIntent().getSerializableExtra(Constants.PRESENT_VALUE);
        Log.i("taskEditInitData", JSONObject.toJSONString(presentValue));
        //获取是新增还是修改还是详情展示
        ModeFlag_Add_Edit_View = presentValue.getFlag();
        projectModel = (ProjectListModel.ProjectModel) presentValue.getT().get("projectModel");
        taskVO = (TaskListModel.TaskVO) presentValue.getT().get("taskVO");
        taskVO = taskVO == null ? new TaskListModel.TaskVO() : taskVO;
        // 获取当前项目总任务数，用于自动生成任务编号
        getMaxTaskNumber();
        // 查询任务详情
        getDetail();
    }

    /**
     * 获取当前项目总任务数，用于自动生成任务编号
     */
    private void getMaxTaskNumber() {
        OkHttp.get("/tpms-plan-service/api/task/get/maxTaskCode/" + projectModel.getId(), null, null, (result -> {
            TaskCountModel countModel = JSONObject.parseObject(result, TaskCountModel.class);
            String maxTaskCode = countModel.getData();
            // 当前任务编号为总任务数 + 1
            maxTaskNumber = Integer.parseInt(maxTaskCode) + 1 + "";
            // 如果当前任务总数为1-9 需要在前面补0
            maxTaskNumber = maxTaskNumber.length() == 1 ? "0" + maxTaskNumber : maxTaskNumber;
        }));
    }

    /**
     * 查询任务详情
     */
    private void getDetail() {
        if (StringUtils.isNotEmpty(taskVO.getId())) {
            OkHttp.get("/tpms-plan-service/api/task/detail/" + taskVO.getId(), null, null, (result -> {
                dtoModel = JSONObject.parseObject(result, TaskDTOModel.class);
                runOnUiThread(() -> {
                    setView(dtoModel.getData());
                });
            }));
        }
    }

    /**
     * 数据回显
     */
    private void setView(TaskDTOModel.TaskDetailModel detailModel) {
        // 调查编号
        _binding.taskCode.setValue(detailModel.getTaskCode());
        // 如果调查类型为 基础设施调查 需要显示调查项
        Integer surveyType = detailModel.getSurveyType();
        if (Enums.TaskInvestigationTypeEnum.TRAFFIC.getKey().equals(surveyType)) {
            _binding.investigationType.setValue(Enums.TaskInvestigationTypeEnum.TRAFFIC.getValue());
        } else {
            _binding.investigationType.setValue(Enums.TaskInvestigationTypeEnum.INFRASTRUCTURE.getValue());
            _binding.investigationTypeChild.setVisibility(View.VISIBLE);
            _binding.investigationTypeChild.setValue(Enums.TaskInvestigationTypeEnum.getValueByKey(surveyType));
        }
        // 调查对象
        surveyObjectList = detailModel.getSurveyObjectList();
        initRecycleView();
        // 任务事项
        _binding.inputTaskMatter.setValue(detailModel.getTaskMatter());
        // 任务人
        setWorkerList(taskUserModelToUserInfo(detailModel.getWorkerUserList()));
        // 任务描述
        _binding.taskDesc.setValue(detailModel.getTaskDesc());
        // 开始时间
        _binding.taskMember1.getSelectTextView().setText(DateUtil.convertDateToString(detailModel.getTaskStartTime(), "yyyy-MM-dd HH:mm:ss"));
        // 结束时间
        _binding.taskMember2.getSelectTextView().setText(DateUtil.convertDateToString(detailModel.getTaskEndTime(), "yyyy-MM-dd HH:mm:ss"));
        // 抄送人
        setCCList(taskUserModelToUserInfo(detailModel.getCcUserList()));
    }

    private List<? extends IUserInfo> taskUserModelToUserInfo(List<TaskUserModel> userModelList) {
        List<UserModel> userInfoList = new ArrayList<>(); // 任务人
        if (CollectionUtils.isEmpty(userModelList)) {
            return userInfoList;
        }
        for (TaskUserModel taskUserModel : userModelList) {
            UserModel userModel = new UserModel();
            userModel.setId(taskUserModel.getUserId());
            userModel.setUsername(taskUserModel.getUserName());
            userModel.setName(taskUserModel.getUserName());
            userModel.setAccountId(taskUserModel.getUserId());
            userInfoList.add(userModel);
        }
        return userInfoList;
    }


    /**
     * 初始化
     */
    private void initView() {
        _binding.taskCode.switchoverMode(false);
        _binding.taskCode.setValue(projectModel.getProjectCode());
    }

    private void initTitleBar() {
        ViewModeValue viewModeValue = new ViewModeValue(this, ModeFlag_Add_Edit_View, _binding.titleBar, _binding.llContainer);

        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(ModeFlag_Add_Edit_View)) {//详情预览
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
            _binding.titleBar.setTitle("详情");
            // 将输入框设为只读
            switchMode(false);
        } else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(ModeFlag_Add_Edit_View)) {
            CommonUtils.setViewMode(viewModeValue, this::returnCheck, this::appendOrModifyData);
            _binding.titleBar.setTitle("新建任务");
        } else if (Constants.PRESENT_VALUE_FLAG.EDIT.equals(ModeFlag_Add_Edit_View)) {
            CommonUtils.setViewMode(viewModeValue, this::returnCheck, this::appendOrModifyData);
            _binding.titleBar.setTitle("任务");
        }

    }

    /**
     * 转换编辑模式
     * @param isEnabled true为可编辑 false不可编辑
     */
    private void switchMode(boolean isEnabled){
        for (int i = 0;i<_binding.llContainer.getChildCount();i++){
            View view = _binding.llContainer.getChildAt(i);
            if (view instanceof BaseInput){
                ((BaseInput) view).switchoverMode(isEnabled);
            }
        }
    }


    // 初始化适配器
    private void initRecycleView() {
        surveyObjectDataAdapter = new SurveyObjectDataAdapter(this);
        surveyObjectDataAdapter.setDataList(surveyObjectList);
        _binding.lRecyclerViewMainRespondents.setAdapter(new LRecyclerViewAdapter(surveyObjectDataAdapter));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        _binding.lRecyclerViewMainRespondents.setLayoutManager(linearLayoutManager);
        _binding.lRecyclerViewMainRespondents.setLoadMoreEnabled(false);
        _binding.lRecyclerViewMainRespondents.setPullRefreshEnabled(false);
    }

    /**
     * 添加调查对象
     */
    private void addSurveyObject() {
        //点击添加
        _binding.btnSurveyObjectAdd.setIronClickListener((view) -> {
            // 最多添加10个调查对象
            if (SURVEY_OBJECT_MAX < surveyObjectList.size()) {
                BamToast.showText(this, "最多只能添加10个调查对象！", false);
            } else {
                //跳转添加调查对象界面
                Intent intent = new Intent(this, SurveyObjectEditActivity.class);
                PresentValue<SurveyObjectModel> presentValue = new PresentValue<>(ModeFlag_Add_Edit_View, new SurveyObjectModel());
                intent.putExtra(Constants.EXTRA_KEY.SURVEY_OBJECT, presentValue);
                /*startActivitylaunch.launch(intent);*/
//            startActivityForResult(intent, PreferincesContext.REQUEST_CODE);

                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::surveyObjectClickListener).launch(intent);
            }
        });
    }

    /**
     * 添加或修改调查对象的回调
     */
    private void surveyObjectClickListener(ActivityResult result) {
        if (result.getData() != null) {
            PresentValue<SurveyObjectModel> value = (PresentValue<SurveyObjectModel>) result.getData().getSerializableExtra(Constants.EXTRA_KEY.SURVEY_OBJECT);
            if (value != null) {
                SurveyObjectModel surveyObjectModel = value.getT();
                if (Constants.PRESENT_VALUE_FLAG.ADD.equals(value.getFlag())) {
                    surveyObjectList.add(surveyObjectModel);
                    surveyObjectDataAdapter.setDataList(surveyObjectList);
                    surveyObjectDataAdapter.notifyDataSetChanged();
                } else if (Constants.PRESENT_VALUE_FLAG.EDIT.equals(value.getFlag())) {
                    if (surveyObjectModel.getPosition() == null || surveyObjectModel.getPosition() < 0) {
                        return;
                    }
                    surveyObjectList.set(surveyObjectModel.getPosition(), surveyObjectModel);
                    surveyObjectDataAdapter.setDataList(surveyObjectList);
                    surveyObjectDataAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    /**
     * 将选中的任务人姓名回显到主页面
     */
    private void setWorkerList(List<? extends IUserInfo> list) {
        if (list == null){
            return;
        }
        _binding.btnWorkerAdd.setValue(StringUtils.getStrWithList(",", list, IUserInfo::getUserName));
        _selectedWorkerList = list;
    }

    /**
     * 将选中的抄送人姓名回显到主页面
     */
    private void setCCList(List<? extends IUserInfo> list) {
        if (list == null){
            return;
        }
        _binding.btnCcAdd.setValue(StringUtils.getStrWithList(",", list, IUserInfo::getUserName));
        _selectedCCList = list;
    }

    /**
     * 新增/修改
     */
    private void appendOrModifyData() {
        if (!checkData()) {
            Log.e(TAG, "新增/修改任务 数据校验失败");
            return;
        }
        Map<String, Object> paramData = paramData();
        Log.i("paramData", JSONObject.toJSONString(paramData));
        String url = "";
        //编辑模式
        if(Constants.PRESENT_VALUE_FLAG.EDIT.equals(ModeFlag_Add_Edit_View)){
            url = "/tpms-plan-service/api/task/update";
        }
        //新增模式
        else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(ModeFlag_Add_Edit_View)){
            url = "/tpms-plan-service/api/task/create";
        } else {
            Log.e(TAG,"新增/修改任务失败 标识不匹配,flag type:" + ModeFlag_Add_Edit_View);
            return;
        }
        OkHttp.post(url, paramData, (result -> {
            JSONObject jsonObject = JSONObject.parseObject(result);
            Log.i(TAG, "create task result is：" + jsonObject);

            String code = (String) jsonObject.get("code");
            assert code != null;

            if (!Enums.ResponseCodeEnum.请求成功.getKey().equals(Integer.valueOf(code))){
                Object msg = jsonObject.get("msg");
                BamToast.showText(this, "请求错误：" + msg);
                return;
            }

            BamToast.showText(this, "保存成功");
            setResult(RESULT_OK, new Intent());
            finish();
        }));
    }

    /**
     * 组装任务人和抄送人列表
     */
    private List<TaskUserModel> paramUser(List<? extends IUserInfo> userInfoList, int userType) {
        List<TaskUserModel> userModelList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userInfoList)) {
            for (IUserInfo userInfo : userInfoList) {
                TaskUserModel taskUserModel = new TaskUserModel();
                taskUserModel.setUserId(userInfo.getUserId());
                taskUserModel.setUserName(userInfo.getUserName());
                taskUserModel.setUserType(userType);
                userModelList.add(taskUserModel);
            }
        }
        return userModelList;
    }

    /**
     * 组装参数
     */
    private Map<String, Object> paramData() {
        Map<String, Object> paramMap = new HashMap<>();
        Integer taskStatus = taskVO.getTaskStatus() == null ? 1 : taskVO.getTaskStatus();
        if (StringUtils.isNotEmpty(taskVO.getId())) {
            paramMap.put("id", taskVO.getId());
        }
        paramMap.put("projectId", projectModel.getId());
        paramMap.put("taskCode", _binding.taskCode.getStringValue());
        paramMap.put("taskStatus", taskStatus); // 先设置默认值为1
        paramMap.put("surveyType", surveyType);
        paramMap.put("taskMatter", _binding.inputTaskMatter.getStringValue());
        paramMap.put("taskDesc", _binding.taskDesc.getStringValue());
        paramMap.put("taskStartTime", _binding.taskMember1.getStringValue());
        paramMap.put("taskEndTime", _binding.taskMember2.getStringValue());
        paramMap.put("surveyObjectList", setSurveyObjectType());
        paramMap.put("workerUserList", paramUser(_selectedWorkerList, USER_TYPE_WORKER));
        paramMap.put("ccUserList", paramUser(_selectedCCList, USER_TYPE_CC));
        return paramMap;
    }

    /**
     * 给调查对象设置调查类型
     */
    private List<SurveyObjectModel> setSurveyObjectType() {
        List<SurveyObjectModel> surveyObjectModels = new ArrayList<>();
        for (SurveyObjectModel surveyObjectModel : surveyObjectList) {
            int type = 0;
            // 获取坐标
            List<LatLng> latLngs = CoorModelChangeUtil.changeToLatLng(surveyObjectModel.getCoordinate());
            // 判断任务的调查类型是基础设施调查还是交通量调查
            if (Enums.TaskInvestigationTypeEnum.TRAFFIC.getKey().equals(surveyType)) {
                // 如果坐标是一个点 说明是路口调查 否为则路段调查
                type = latLngs.size() == 1 ? Constants.SurveyObjectType.ROAD_INTERSECTION_TRAFFFIC : Constants.SurveyObjectType.ROAD_SECTION_TRAFFFIC;
            } else {
                type = latLngs.size() == 1 ? Constants.SurveyObjectType.ROAD_INTERSECTION_FACILITIES : Constants.SurveyObjectType.ROAD_SECTION_FACILITIES;
            }
            surveyObjectModel.setType(type);
            surveyObjectModels.add(surveyObjectModel);
        }
        return surveyObjectModels;
    }

    /**
     * 获取调查类型
     */
    private void getSurveyType() {
        String investigationType = _binding.investigationType.getStringValue();
        // 如果调查类型选中的是基础设施调查，则取调查项的值
        if (Enums.TaskInvestigationTypeEnum.INFRASTRUCTURE.getValue().equals(investigationType)) {
            surveyType = Enums.TaskInvestigationTypeEnum.getKeyByValue(_binding.investigationTypeChild.getStringValue());
        } else {
            surveyType = Enums.TaskInvestigationTypeEnum.getKeyByValue(_binding.investigationType.getStringValue());
        }
    }

    /**
     * 必填项校验
     */
    private boolean checkData() {
        getSurveyType();
        String taskCode = _binding.taskCode.getStringValue(); // 任务编号
        // 任务编号，调查类型，调查对象，任务人不能为空
        if (StringUtils.isEmpty(taskCode) || surveyType == null
                || CollectionUtils.isEmpty(surveyObjectList) || CollectionUtils.isEmpty(_selectedWorkerList)) {
            BamToast.showText(this, R.string.requires_text_filed_check, false);
            return false;
        }
        return true;
    }

    /**
     * 删除任务
     */
    private void deleteData() {
        if (StringUtils.isNotEmpty(taskVO.getId())) {
            OkHttp.post("/tpms-plan-service/api/task/delete/" + taskVO.getId(), new HashMap<>(), (result -> {
                Log.i(TAG, "delete task result is：" + result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = (String) jsonObject.get("code");
                assert code != null;

                if (!Enums.ResponseCodeEnum.请求成功.getKey().equals(Integer.valueOf(code))){
                    Object msg = jsonObject.get("msg");
                    BamToast.showText(this, "请求错误：" + msg);
                    return;
                }

                BamToast.showText(this, "删除成功");
                setResult(RESULT_OK, new Intent());
                finish();
            }));
        }
    }

    private void returnCheck() {
        finish();
    }

    private void callMoreMenu() {
        CommonUtils.showMoreMenu(this, _binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void linkToEditActivity() {
        Intent intent = new Intent(this, TaskEditActivity.class);
        // 组装传递对象
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("projectModel", projectModel);
        paramMap.put("taskVO", taskVO);
        PresentValue<Map<String, Object>> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.EDIT, paramMap);
        intent.putExtra(Constants.PRESENT_VALUE, presentValue);
        startActivity(intent);
    }


    @OnClick({R.id.btn_worker_add, R.id.btn_cc_add, R.id.task_Member1, R.id.task_Member2, R.id.investigation_type, R.id.investigation_type_child})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_worker_add: {
                Intent intent = new Intent(this, MemberSelectActivity.class);
                PresentValue<List<? extends IUserInfo>> presentValue = new PresentValue<>(MemberSelectActivity.SELECTED_MEMBERS_KEY, _selectedWorkerList);
                intent.putExtra(Constants.PRESENT_VALUE, presentValue);
                // 任务人
                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            List<SelectUserModel> selectedArr = (List<SelectUserModel>) OneOffCupboard.sharedInstance().getThenRemove(MemberSelectActivity.SELECTED_MEMBERS_KEY);
                            setWorkerList(selectedArr);
                        }
                    }
                }).launch(intent);

                break;
            }
            case R.id.btn_cc_add: {
                Intent intent = new Intent(this, MemberSelectActivity.class);
                PresentValue<List<? extends IUserInfo>> presentValue = new PresentValue<>(MemberSelectActivity.SELECTED_MEMBERS_KEY, _selectedCCList);
                intent.putExtra(Constants.PRESENT_VALUE, presentValue);
                // 抄送人
                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            List<SelectUserModel> selectedArr = (List<SelectUserModel>)OneOffCupboard.sharedInstance().getThenRemove(MemberSelectActivity.SELECTED_MEMBERS_KEY);
                            setCCList(selectedArr);
                        }
                    }
                }).launch(intent);

                break;
            }
            case R.id.task_Member1: {
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertTimerPicker(_binding.taskMember1.getSelectTextView(), TimePickerView.Type.ALL, "yyyy-MM-dd HH:mm:ss", new RollUtil.TimerPickerCallBack() {
                    @Override
                    public void onTimeSelect(String date) {
                        _binding.taskMember1.getSelectTextView().setText(date);
                    }
                });
                break;
            }
            case R.id.task_Member2: {
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertTimerPicker(_binding.taskMember2.getSelectTextView(), TimePickerView.Type.ALL, "yyyy-MM-dd HH:mm:ss", new RollUtil.TimerPickerCallBack() {
                    @Override
                    public void onTimeSelect(String date) {
                        _binding.taskMember2.getSelectTextView().setText(date);
                    }
                });
                break;
            }
            case R.id.investigation_type: {
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, surveyTypeDict, _binding.investigationType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        // 如果调查类型为 基础设施调查 则展示调查项菜单
                        if (0 == index) {
                            _binding.investigationTypeChild.setVisibility(View.VISIBLE);
                            // 组装任务编号
                            _binding.taskCode.setValue(projectModel.getProjectCode() + "_01_" + maxTaskNumber);
                        } else {
                            _binding.investigationTypeChild.setVisibility(View.GONE);
                            _binding.investigationTypeChild.setValue("");
                            // 组装任务编号
                            _binding.taskCode.setValue(projectModel.getProjectCode() + "_02_" + maxTaskNumber);
                        }
                        _binding.investigationType.setValue(surveyTypeDict.get(index));
                    }
                });
                break;
            }
            case R.id.investigation_type_child: {
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, surveyTypeChildDict, _binding.investigationTypeChild.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        _binding.investigationTypeChild.setValue(surveyTypeChildDict.get(index));
                    }
                });
                break;
            }
        }
    }

    private Set<IteamSlideLayout> sets = new HashSet<>();

    // 修改或删除调查对象
    private void editSurveyObject(SurveyObjectModel model, String type) {
        if (Constants.PRESENT_VALUE_FLAG.EDIT.equals(type) || Constants.PRESENT_VALUE_FLAG.VIEW.equals(type)
                || Constants.PRESENT_VALUE_FLAG.ADD.equals(type)) {
            Intent intent = new Intent(this, SurveyObjectEditActivity.class);
            PresentValue<SurveyObjectModel> presentValue = new PresentValue<>(ModeFlag_Add_Edit_View, model);
            intent.putExtra(Constants.EXTRA_KEY.SURVEY_OBJECT, presentValue);

            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::surveyObjectClickListener).launch(intent);
        } else if (Consts.OperationType.DELETE.equals(type)) {
            CommonUtils.doubleBtnDialog(this, () -> {
                surveyObjectList.remove(model);
                surveyObjectDataAdapter.setDataList(surveyObjectList);
                surveyObjectDataAdapter.notifyDataSetChanged();
            });
            if (sets.size() > 0) {
                for (IteamSlideLayout s : sets) {
                    s.close();
                }
            }
        }
    }

    //监听滑动
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (sets.size() > 0) {
                for (IteamSlideLayout s : sets) {
                    if (ViewUtils.isClickNotInView(s.getMenuView(), event)) {
                        s.close();
                        return true;
                    }
                }
            }
        }
        return ViewUtils.dispatchTouchEvent(this, event);
    }

    /**
     * 调查对象式适配器
     * 将保存的调查对象名称回显至任务列表
     */
    private class SurveyObjectDataAdapter extends ListBaseAdapter<SurveyObjectModel> {

        public SurveyObjectDataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_road_name_and_level;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView title = holder.getView(R.id.tv_common_title);
            View content = holder.getView(R.id.content);
            TextView level = holder.getView(R.id.tv_level);
            TextView delete = holder.getView(R.id.tv_delete);
            SurveyObjectModel model = mDataList.get(position);
            title.setText(model.getSurveyName());
            level.setText("");
            model.setPosition(position);
            IteamSlideLayout layout = (IteamSlideLayout) holder.itemView;
            layout.setOnStateChangeListener(new MyOnStateChangeListener());
            content.setOnClickListener(v -> editSurveyObject(model, ModeFlag_Add_Edit_View));
            delete.setOnClickListener(v -> editSurveyObject(model, Consts.OperationType.DELETE));
        }
    }

    //实现删除按钮滑动状图改变监听事件，可以灵活存储当前打开的是哪一个，以便后面的优化
    private class MyOnStateChangeListener implements IteamSlideLayout.OnStateChangeListener {
        public IteamSlideLayout slideLayout = null;

        @Override
        public void onOpen(IteamSlideLayout layout) {
            slideLayout = layout;
            if (sets.size() > 0) {
                for (IteamSlideLayout s : sets) {
                    s.close();
                }
            }
            sets.add(layout);
        }

        @Override
        public void onMove(IteamSlideLayout layout) {
        }

        @Override
        public void onClose(IteamSlideLayout layout) {
            if (sets.size() > 0) {
                sets.remove(layout);
            }
            if (slideLayout == layout) {
                slideLayout = null;
            }
        }
    }
}
